What is caller-path?
The caller-path npm package is designed to help developers retrieve the path of the file that calls a function. This can be particularly useful for debugging, logging, and tracking the flow of a program, especially in complex applications where functions are called from multiple places.
What are caller-path's main functionalities?
Get caller file path
This feature allows developers to log or retrieve the path of the file that called a function. In the provided code, the function `whoCalled` uses `callerPath()` to print the path of the caller file.
const callerPath = require('caller-path');
function whoCalled() {
console.log(callerPath());
}
module.exports = whoCalled;
Other packages similar to caller-path
callsites
The 'callsites' package provides functionality to get the call sites (stack frames) of the V8 stack trace API, which can be used to find the path of the caller. It offers more detailed control over the stack trace compared to caller-path, allowing developers to access deeper insights into the call stack.
stack-trace
This package is used to extract a stack trace from within a running node.js application, similar to caller-path. It differs in that it provides a more comprehensive set of features for manipulating and analyzing the stack trace beyond just retrieving the caller's path.
caller-path
Get the path of the caller function
Important: You have to use 'use strict';
in your code for this module to work correctly, or make sure the module is an ESM module, which is implicitly strict.
Install
$ npm install caller-path
Usage
const callerPath = require('caller-path');
module.exports = () => {
console.log(callerPath());
}
const foo = require('./foo');
foo();
If the caller's callsite object getFileName
was not defined for some reason, it will return undefined
.
API
callerPath(options?)
Get the path of the caller function.
depth
Type: number
Default: 0
The caller path depth, meaning how many levels we follow back on the stack trace.
For example:
const callerPath = require('caller-path');
module.exports = () => {
console.log(callerPath());
console.log(callerPath({depth: 1}));
console.log(callerPath({depth: 2}));
}
const foo = require('./foo');
module.exports = () => {
foo();
}
const bar = require('./bar');
bar();